#include "addweburl.h"
#include "ui_addweburl.h"

#include <QTextBlock>
#include <QMessageBox>

AddWebUrl::AddWebUrl(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddWebUrl)
{
    ui->setupUi(this);
}

AddWebUrl::~AddWebUrl()
{
    delete ui;
}

/**
 * 添加采集的网址到父窗口中
 */
void AddWebUrl::on_pushButton_clicked()
{
    // 获取行数
    // int lineNum = ui->plainTextEdit->document()->lineCount();
    // qDebug() << lineNum;

    // blockCount()不考虑由自动换行造成的额外行
    int blockCount = ui->plainTextEdit->document()->blockCount();
    qDebug() << "文本块数:" << blockCount;

    QStringList webUrls;
    QString lineStr;


    for (int i = 0; i < blockCount; ++i)
    {
        lineStr = ui->plainTextEdit->document()->findBlockByLineNumber(i).text();

        qDebug() << lineStr;

        if(lineStr.isEmpty())
        {
            QMessageBox::information(this, "提示", "请输入需要采集数据的网址");
            return;
        }
        // 检测是否是正确的网址格式
        if(!this->checkUrls(lineStr))
        {
            QMessageBox::information(this, "提示", "地址不是以http://或https://开头，请确认");
            return;
        }
        webUrls.append(lineStr);
    }

    emit LineWebUrl(webUrls);

    this->close();
}

/**
 * @brief AddWebUrl::checkUrls
 * 检测网址格式是否正确
 */
bool AddWebUrl::checkUrls(const QString &url)
{
    QUrl urlObject(url);
    return urlObject.isValid() && (urlObject.scheme() + "://" == "http://" || urlObject.scheme() + "://" == "https://");
}
